package com.guos.bio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 每一行代码，都是改变世界的力量
 *
 * @author 郭帅
 * @date 2022/6/22 3:07 下午
 */
public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(8080));
        byte[] bytes = new byte[5];
        while (true) {
            // 阻塞，等待接收客户端连接
            System.out.println("wait connect...");
            Socket socket = serverSocket.accept();// 阻塞
            System.out.println("connected:" + socket);

            // 使用线程去执行连接读操作
            new Thread(() -> {
                StringBuilder builder = new StringBuilder();
                while (true) {
                    try {
                        int i = socket.getInputStream().read(bytes);//阻塞方法
                        if (i > 0) {
                            for (int j = 0; j < i; j++) {
                                builder.append((char) bytes[j]);
                            }
                        }
                        if (i == 0 || i < bytes.length) {
                            System.out.println(socket + ": " + builder);
                            builder = new StringBuilder();
                        }
                        if (i < 0) {
                            System.out.println("unconnected..:" + socket);
                            break;
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
